package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.RedisKeyConstant;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.dto.AlertDataDto;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.system.mapper.SysUserMapper;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.AlertDataMapper;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 * 
 * @author iteheima
 * @date 2025-03-18
 */
@Service
@Slf4j
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService
{
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;


    /**
     * 查询报警数据
     * 
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     * 
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData)
    {
        return alertDataMapper.selectAlertDataList(alertData);
    }

    /**
     * 新增报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData)
    {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData)
    {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     * 
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     * 
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }



    /**
     * 分页查询报警数据
     * @param pageNum
     * @param pageSize
     * @param deviceName
     * @param startTime
     * @param endTime
     * @param id
     * @param status
     * @return
     */
    @Override
    public List<AlertData> findByPage(Integer pageNum, Integer pageSize, String deviceName, LocalDateTime startTime, LocalDateTime endTime, Integer id, Integer status) {
        // 注意：只有负责该老人的护理员才能看到报警数据
        // 获取当前登录人id
        Long userId = SecurityUtils.getUserId();
        Page<AlertData> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<AlertData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(deviceName), AlertData::getDeviceName, deviceName)
                    .between(ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime),
                            AlertData::getProcessingTime,
                            startTime,
                            endTime)
                    .eq(ObjectUtil.isNotEmpty(userId),AlertData::getUserId, userId)
                    .eq(ObjectUtil.isNotEmpty(status), AlertData::getStatus, status)
                    .eq(ObjectUtil.isNotEmpty(id), AlertData::getId, id);

        page(page, queryWrapper);

//        AlertData alertData = getById(id);
//        if(ObjectUtil.isEmpty(alertData)){
//            throw new BaseException("报警信息为空");
//        }
//        String iotId = alertData.getIotId();
//        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
//        queryWrapper1.eq(Device::getIotId, iotId);
//        Device device = deviceMapper.selectOne(queryWrapper1);
//        if(ObjectUtil.isEmpty(device)){
//            throw new BaseException("设备不存在");
//        }
//        String nodeId = device.getNodeId();
//        alertData.setNickname(nodeId);

        return page.getRecords();
    }

    @Autowired
    private ISysUserService sysUserService;


    @Override
    public void handleAlertData(AlertDataDto alertDataDto) {
//        如果老人被多个护理员负责，那么多个护理员都可以看到这条数据
//        当其中一个护理员处理数据之后，其他负责的护理员也会展示已处理

        // 获得报警数据对象
        AlertData alertDataBean = getById(alertDataDto.getId());
        if(ObjectUtil.isEmpty(alertDataBean)){
            throw new BaseException("报警数据不存在");
        }
        Long userId = SecurityUtils.getUserId();
        // 如果设备名称 相同，且创建时间相同，则认为同一个报警数据(只是他们的接收人可以有多个)，给他们设置相同的处理数据
        List<AlertData> alertDataList = list(new LambdaQueryWrapper<AlertData>()
                .eq(AlertData::getDeviceName, alertDataBean.getDeviceName())
                .eq(AlertData::getCreateTime, alertDataBean.getCreateTime()));
        // 遍历集合，拿到每一个报警数据，设置处理结果，处理时间，处理人，处理状态
        for (AlertData alertData : alertDataList) {
            alertData.setStatus(1);
            alertData.setProcessorId(userId);
            alertData.setProcessingResult(alertDataDto.getProcessingResult());
            alertData.setProcessingTime(alertDataDto.getProcessingTime());
            alertData.setProcessorName(SecurityUtils.getUsername());
        }
        updateBatchById(alertDataList);
    }
}
